package me.seu.demo.algorithms.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 二叉树的层序遍历
 *
 * @author liangfeihu
 * @since 2021/2/20 下午4:07
 */
public class TreeLevelOrder {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = queue.size();

        while (!queue.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            while (count > 0) {
                TreeNode cur = queue.poll();
                temp.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
                count--;

                if (count == 0) {
                    res.add(temp);
                }
            }

            // 当前层节点个数
            count = queue.size();
        }
        return res;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        TreeNode treeNode = new TreeNode(20);
        root.right = treeNode;
        treeNode.left = new TreeNode(15);
        treeNode.right = new TreeNode(7);

        List<List<Integer>> lists = levelOrder(root);
        System.out.println(lists.toString());

        List<List<Integer>> lists2 = levelOrderV2(root);
        System.out.println(lists2.toString());
    }

    public static List<List<Integer>> levelOrderV2(TreeNode root) {
        List<List<Integer>> resList = new ArrayList<>();
        if (root == null) {
            return resList;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        int size = queue.size();
        while (!queue.isEmpty()) {
            List<Integer> temp = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }

            resList.add(temp);

            size = queue.size();
        }

        return resList;
    }

}
